package com.cp.config;

import com.cp.properties.CpRedisProperties;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * Des:
 * RedisTemplate序列化
 *
 * @author XL
 * @Date 2022/2/16 18:53
 */
@Import(CpRedisProperties.class)
@EnableConfigurationProperties(CpRedisProperties.class)
public class CpRedisAutoConfiguration {

    @Value("${spring.application.name}")
    private String applicationName;

    @Bean("redisTemplate")
    @Primary
    public RedisTemplate<Object, Object> createRedisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        CpRedisJsonSerializer<Object> fastJsonRedisSerializer = new CpRedisJsonSerializer<>(Object.class);
        template.setKeySerializer(new CpKeyStringSerializer(applicationName));
        template.setHashKeySerializer(new CpKeyStringSerializer(applicationName));
        // value值的序列化采用CpRedisJsonSerializer
        template.setValueSerializer(fastJsonRedisSerializer);
        template.setHashValueSerializer(fastJsonRedisSerializer);
        // key的序列化采用StringRedisSerializer
        return template;
    }
}
